import random

from flask import Blueprint, render_template

from App.ext import db
from .models import Student

# blue = Blueprint('blue', __name__, template_folder='../templates')
blue = Blueprint('blue', __name__, )


def init_blue(app):
    app.register_blueprint(blue)


@blue.route('/')
def index():
    return 'index'


@blue.route('/addstudent/')
def add_student():
    student = Student()
    student.name = '小花%d' % random.randrange(1000000)
    db.session.add(student)
    db.session.commit()

    print(type(db.session))
    print(db.session)

    return 'add success'


@blue.route('/addstudents/')
def add_students():
    students = []
    for i in range(10):
        student = Student()
        student.name = '小明%d' % i
        students.append(student)
    db.session.add_all(students)
    db.session.commit()
    print(type(db.session))
    print(db.session)
    return 'add students success'


@blue.route('/getstudent/')
def get_student():
    student = Student.query.get_or_404(2)
    return student.name


@blue.route('/getstudents/')
def get_students():
    students = Student.query.all()
    for student in students:
        print(student.name)
    # return 'get all students'
    return render_template("StudentList.html", students=students)


@blue.route('/deletestudent/')
def delete_student():
    student = Student.query.get_or_404(1)
    db.session.delete(student)
    db.session.commit()

    return 'delete success'


@blue.route('/updatestudent/')
def update_student():
    student = Student.query.first()
    student.name = 'tom'
    db.session.add(student)
    db.session.commit()

    return 'update success'
